from dvadmin.lowcode.models import Datasource
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from rest_framework import serializers
from dvadmin.utils.common import get_parameter_dic
import json

class DatasourceSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """

    class Meta:
        model = Datasource
        # fields = "__all__"
        exclude = ['password']  # 排除字段2

        read_only_fields = ["id"]


class TreeSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    value = serializers.IntegerField(source="id")
    label = serializers.CharField(source="name")

    class Meta:
        model = Datasource
        fields = '__all__'
        fields = ('label', 'value')


# class AssetsViewSet(CustomModelViewSet):
#     """
#     物料管理
#     list:查询
#     create:新增
#     update:修改
#     retrieve:单例
#     destroy:删除
#     """
#     queryset = OnlineApi.objects.all()
#     serializer_class = OnlineApiSerializer


class SchemaPerViewSet(CustomModelViewSet):
    """
    在线接口管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = Datasource.objects.all()
    serializer_class = DatasourceSerializer
    extra_filter_backends = []

    @action(methods=['GET'], detail=False, permission_classes=[])
    def tree(self, request):
        """用于前端菜单树结构树"""
        self.queryset.filter(status = 1)
        serializer = TreeSerializer(self.queryset.all(), many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, total=len(data), msg="获取成功")
    @action(methods=['POST'], detail=False)
    def databasetest(self, request):
        """数据库连接测试"""
        data = get_parameter_dic(request)
        host = data.get('host',None)
        id = data.get('id',None)
        port = data.get('port',None)
        user = data.get('user',None)
        password = data.get('password',None)
        database = data.get('database',None)
        key = data.get('key',None)
        datatype = data.get('datatype',None)
        if not password:
            return ErrorResponse(data=[], msg="无效的密码")
        if not datatype and host:
            return ErrorResponse(data=[], msg="错误的参数")
        if datatype == 1:
            from ..utils.mysql import mysqlhandel
            da,err = mysqlhandel.testconnect(host,port,user,password,database)
            if da:
                return DetailResponse(data=[],msg='连接成功')
            return ErrorResponse(data=[],msg=str(err))
        if datatype == 2:
            from ..utils.mongodb import mongodbInit
            da,err = mongodbInit.testconnect(host,port,user,password,database)
            if da:
                return DetailResponse(data=[],msg='连接成功')
            return ErrorResponse(data=[],msg=str(err))
        elif datatype == 3:
            from ..utils.es import ElastSearchInit
            da,err = ElastSearchInit.testconnect(host,port,user,password,database)
            if da:
                return DetailResponse(data=[],msg='连接成功')
            return ErrorResponse(data=[],msg=str(err))
        return ErrorResponse(data=[], msg="连接失败")


